package mobi.zeedev.flyingsaucer.common.RegexModule;

//import roboguice.util.Ln;

import roboguice.util.Ln;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class RegexHandler2<A, T> {

    public Boolean continueReceiving = null;
    public T temporaryStorage = null;
    public A accumlatedResult = null;


    public A regexProcess(String regexIn, String data, Integer flags) {
        Pattern p = flags != null ? Pattern.compile(regexIn, flags) : Pattern.compile(regexIn);
        return regexProcess(p, data);
    }

    public A regexProcess(Pattern regexPattern, String data) {

        Matcher m = regexPattern.matcher(data);

        Boolean cont = true;
        while (cont) {

            while (continueReceiving) {
                if (m.find()) {
                    MatchResult mr = m.toMatchResult();

                    process(mr, accumlatedResult, temporaryStorage);

                } else {
                    cont = false;
                    continueReceiving = false;
                }
            }
        }


        return accumlatedResult;
    }

    public RegexHandler2(boolean instantiateContainers) {
        super();
        continueReceiving = true;
        try {
            if (instantiateContainers) {
                this.temporaryStorage = (T) temporaryStorage.getClass().newInstance();
                this.accumlatedResult = (A) accumlatedResult.getClass().newInstance();
            }
        } catch (IllegalAccessException e) {
            Ln.e(e);
        } catch (InstantiationException e) {
            Ln.e(e);
        }
    }


    private void process(MatchResult matchIn, A acc, T temp) {
        if (accumlatedResult == null) {
            onAccumulatedResultNull(acc, temp);
        }
        if (temporaryStorage == null) {
            onTemporaryStorageNull(acc, temp);
        }
        onProcess(matchIn);
    }


    //this can be anything that ... you need for data storage
    public abstract void onTemporaryStorageNull(A acc, T temp);

    //Create new object to accumlate
    public abstract void onAccumulatedResultNull(A acc, T temp);

    public abstract void onProcess(MatchResult match);

}
